﻿using System;
using System.Diagnostics;
using System.Management;
using System.Threading;

namespace ConsoleDemo
{
    public class ProgramBeauty
    {
        //让 CPU 的占用率固定在50%，为一条直线。
        public static void CpuUsageRate()
        {
            int level = 50;
            PerformanceCounter p = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            if (p == null)
            {
                return;
            }
            while (true)
            {
                if (p.NextValue() > level)
                    System.Threading.Thread.Sleep(100);
            }

            //Console.WriteLine(System.Environment.TickCount);
        }


        //获取CPU的信息，让线程在指定处理器上运行。
        public static void CpuInfo()
        {
            Console.WriteLine($"逻辑处理器数量: {Environment.ProcessorCount}");

            // 获取物理处理器（CPU）和核心的信息（需要System.Management）  
            try
            {
                var searcher = new ManagementObjectSearcher("Select * from Win32_Processor");

                foreach (var share in searcher.Get())
                {
                    // CPU ID、制造商、名称等信息  
                    string cpuId = share["ProcessorId"].ToString();
                    string manufacturer = share["Manufacturer"].ToString();
                    string name = share["Name"].ToString();
                    int maxClockSpeed = (int)(uint)share["MaxClockSpeed"];
                    int numberOfCores = (int)(uint)share["NumberOfCores"];
                    int numberOfLogicalProcessors = (int)(uint)share["NumberOfLogicalProcessors"];

                    Console.WriteLine($"CPU ID: {cpuId}");
                    Console.WriteLine($"Manufacturer: {manufacturer}");
                    Console.WriteLine($"Name: {name}");
                    Console.WriteLine($"Max Clock Speed: {maxClockSpeed} MHz");
                    Console.WriteLine($"Number Of Cores: {numberOfCores}");
                    Console.WriteLine($"Number Of Logical Processors: {numberOfLogicalProcessors}");
                    Console.WriteLine($"Processor Name: {share["Name"]}");
                    Console.WriteLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error fetching CPU information: " + ex.Message);
            }

            // 获取当前进程的主线程
            Process currentProcess = Process.GetCurrentProcess();
            currentProcess.ProcessorAffinity = new IntPtr(1 << 15);

            Console.WriteLine($"进程已设置为在指定处理器上运行。");
        }

        // 成功
        // CPU 主频 2.5GHz, 即 2,400,000,000（25亿）
        // loopIterations 数值   120,000,000 (1亿)
        public static void TryMaintainCpuUsageAround50Percent()
        {
            PerformanceCounter _cpuUsageCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");

            const double targetUsage = 50.0; // 目标 CPU 使用率（百分比）
            const int adjustmentIntervalMs = 100;  // 采样间隔（毫秒）  
            int minLoopIterations = 1000_0000;
            int maxLoopIterations = 110000000;

            while (true)
            {
                // 初始猜测的循环迭代次数
                int loopIterations = (minLoopIterations + maxLoopIterations) / 2;

                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();

                // 执行"工作"循环
                for (int i = 0; i < loopIterations; i++)
                {
                    // 这里只是示例，实际没有做任何有用的工作，仅用于消耗CPU时间
                }

                stopwatch.Stop();

                // 计算当前CPU使用率
                double currentUsage = _cpuUsageCounter.NextValue();


                // 根据当前使用率调整下次循环的迭代次数
                if (currentUsage > targetUsage)
                {
                    // 如果当前使用率过高，减少迭代次数
                    maxLoopIterations = loopIterations;
                }
                else
                {
                    // 如果当前使用率过低，增加迭代次数
                    minLoopIterations = loopIterations;
                    //Console.WriteLine(loopIterations);
                }

                // 简单的延迟，避免过于频繁的调整
                Thread.Sleep(adjustmentIntervalMs);
            }
        }
    }
}
